<template>
  <div class="chat-container">
    <!-- 气泡消息列表 -->
    <BubbleList :list="messages" :reverse="false" />

    <!-- 思考链组件（用于渲染SSE返回的思考内容） -->
    <ThoughtChain
        v-if="currentThoughtChain"
        :chain="currentThoughtChain"
        :collapsed="isThoughtChainCollapsed"
        @toggle="toggleThoughtChain"
    />

    <!-- 智能输入框（发送消息并建立SSE连接） -->
    <Sender
        v-model="inputValue"
        :loading="isSending"
        :disabled="isSending"
        @send="sendMessage"
        @stop="stopSSE"
    >
      <template #prefix>
        <el-button @click="toggleThoughtChainDisplay">
          <span>显示思考链</span>
        </el-button>
      </template>
    </Sender>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { BubbleList, Sender, ThoughtChain } from 'vue-element-plus-x';
import { ElButton, ElIcon } from 'element-plus';
import { useXStream } from 'vue-element-plus-x';

// 状态管理
const inputValue = ref('');
const messages = ref([
  {
    id: 'init-1',
    role: 'system',
    content: '👋 请输入问题，我将通过SSE流式返回思考过程与答案',
    datetime: new Date().toLocaleString()
  }
]);
const currentThoughtChain = ref(null);
const isThoughtChainCollapsed = ref(true);
const showThoughtChain = ref(true);
const isSending = ref(false);
const sseSource = ref(null);

// 流式响应处理
const { streamRequest, isLoading } = useXStream({
  url: '/api/ai/manus/chat', // SSE接口地址
  method: 'GET',
  transformResponse: (chunk) => {
    try {
      return JSON.parse(chunk); // 解析SSE返回的JSON数据
    } catch (e) {
      return { content: chunk, reaContent: '' };
    }
  }
});

// 发送消息并建立SSE连接
const sendMessage = async (value) => {
  if (!value.trim() || isSending.value) return;

  // 添加用户消息
  const userMsg = {
    id: `user-${Date.now()}`,
    role: 'user',
    content: value,
    datetime: new Date().toLocaleString()
  };
  messages.value.push(userMsg);

  // 添加AI回复占位
  const aiMsg = {
    id: `ai-${Date.now()}`,
    role: 'ai',
    content: '',
    datetime: new Date().toLocaleString(),
    isLoading: true
  };
  messages.value.push(aiMsg);

  // 初始化思考链
  if (showThoughtChain.value) {
    currentThoughtChain.value = {
      id: `chain-${Date.now()}`,
      title: '思考过程',
      steps: [
        {
          id: 'step-1',
          title: '问题分析',
          content: '正在解析用户问题...',
          status: 'loading',
          time: new Date().toLocaleString()
        }
      ]
    };
  }

  // 建立SSE连接
  isSending.value = true;
  try {
    await streamRequest(
        { message: value }, // 传递用户消息到SSE接口
        {
          onStart: () => {
            console.log('SSE连接已建立');
          },
          onData: (chunk) => {
            // 处理SSE返回的流式数据
            const lastMsgIndex = messages.value.length - 1;
            const lastMsg = messages.value[lastMsgIndex];

            // 更新AI回复内容
            if (chunk.content) {
              lastMsg.content += chunk.content;
              lastMsg.isLoading = false;
            }

            // 更新思考链内容
            if (showThoughtChain.value && chunk.reaContent) {
              const steps = chunk.reaContent.split('\n\n').filter(step => step.trim());
              currentThoughtChain.value.steps = steps.map((step, idx) => ({
                id: `step-${idx+1}`,
                title: `步骤 ${idx+1}`,
                content: step,
                status: 'completed',
                time: new Date().toLocaleString()
              }));
            }

            messages.value = [...messages.value]; // 触发更新
          },
          onError: (error) => {
            console.error('SSE错误:', error);
            const lastMsgIndex = messages.value.length - 1;
            messages.value[lastMsgIndex].content = '抱歉，获取回复时出错，请重试';
            messages.value[lastMsgIndex].isLoading = false;
          },
          onComplete: () => {
            isSending.value = false;
            const lastMsgIndex = messages.value.length - 1;
            messages.value[lastMsgIndex].isLoading = false;

            // 思考链添加总结步骤
            if (showThoughtChain.value) {
              currentThoughtChain.value.steps.push({
                id: 'step-summary',
                title: '总结',
                content: '已完成思考并生成答案',
                status: 'completed',
                time: new Date().toLocaleString()
              });
            }
          }
        }
    );
  } catch (error) {
    console.error('发送请求失败:', error);
    const lastMsgIndex = messages.value.length - 1;
    messages.value[lastMsgIndex].content = '抱歉，发送消息时出错，请重试';
    messages.value[lastMsgIndex].isLoading = false;
    isSending.value = false;
  }
};

// 停止SSE连接
const stopSSE = () => {
  streamRequest.abort();
  isSending.value = false;
  const lastMsgIndex = messages.value.length - 1;
  if (lastMsgIndex >= 0) {
    messages.value[lastMsgIndex].isLoading = false;
  }
};

// 切换思考链显示状态
const toggleThoughtChainDisplay = () => {
  showThoughtChain.value = !showThoughtChain.value;
  if (!showThoughtChain.value) {
    currentThoughtChain.value = null;
  }
};

// 切换思考链折叠状态
const toggleThoughtChain = () => {
  isThoughtChainCollapsed.value = !isThoughtChainCollapsed.value;
};

// 清理SSE连接
onUnmounted(() => {
  if (sseSource.value) {
    sseSource.value.close();
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.bubble-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.sender-container {
  position: relative;
}
</style>